<template>
    <div>
        <div style="width: 100%; height: 500px" ref="chartRef" />
    </div>
</template>
<script lang="ts">
import { isNotEmpty } from '@/utils/is';
import { useEcharts } from '@/hooks/common/useEcharts';
import { defineComponent, ref, unref, watch } from 'vue';
export default defineComponent({
    name: 'HBarChart',
    props: {
        option: { type: Object, default: () => ({}) }
    },
    setup(props) {
        const chartRef = ref<any>();
        const defaultOption: any = ref({
            title: {
                text: '', //主标题
                textStyle: {
                    fontSize: '16px',
                    color: '#172B4D',
                    fontWeight: 'normal'
                },
                bottom: 0,
                x: 'center'
            },
            color: null,
            legend: {},
            grid: {
                bottom: '30%'
            },
            xAxis: {
                type: 'category',
                data: [],
                nameLocation: 'end',
                axisTick: {
                    show: true //显示坐标轴刻度线
                },
                axisLine: {
                    show: true //显示坐标轴线
                },
                axisLabel: {
                    //坐标轴刻度标签的相关设置。
                    interval: 0,
                    rotate: '-45'
                }
            },
            yAxis: {},
            series: [],
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            }
        });
        const { setOptions } = useEcharts(chartRef, defaultOption, ['#40AD7E', '#1AA5D7', '#FF9845']);
        const updateChart = () => {
            // 先清空
            defaultOption.value.series = [];
            const { legend, typeArr, xArr, series, title, yAxis, tooltip } = props.option;
            defaultOption.value.legend = legend;
            defaultOption.value.yAxis = yAxis;
            defaultOption.value.tooltip = tooltip || {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            };
            if (typeArr && typeArr.length) {
                defaultOption.value.legend.data = [...typeArr];
            }
            defaultOption.value.xAxis.data = xArr; // 横坐标分类
            defaultOption.value.title = {
                ...defaultOption.value.title,
                ...title
            };
            defaultOption.value.series = series;
            setOptions(unref(defaultOption));
        };
        watch(
            () => props.option,
            (n) => {
                if (isNotEmpty(n)) {
                    updateChart();
                }
            },
            { deep: true }
        );
        return {
            chartRef
        };
    }
});
</script>

